package com.party.mobile.biz.gift;

import com.google.common.collect.Lists;
import com.party.core.model.crowdfund.Project;
import com.party.core.model.gift.GiftMember;
import com.party.core.model.gift.GiftOrder;
import com.party.core.model.gift.GiftTarget;
import com.party.core.model.gift.TargetCondition;
import com.party.core.service.gift.IGiftMemberService;
import com.party.core.service.gift.IGiftOrderService;
import com.party.core.service.gift.IGiftService;
import com.party.core.service.gift.IGiftTargetService;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.web.dto.login.output.CurrentUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author： yifeng
 * @description： 礼包业务
 * @date：Created in  2017/12/14 上午 11:40
 **/
@Service
public class GiftTargetBizService {
    @Autowired
    private IGiftService giftService;
    @Autowired
    private IGiftOrderService giftOrderService;
    @Autowired
    private IGiftTargetService giftTargetService;
    @Autowired
    private CurrentUserBizService currentUserBizService;
    @Autowired
    private IGiftMemberService giftMemberService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 众筹场景礼包
     *
     * @param targetId 项目id
     * @param project  众筹实体
     * @param giftFlag 报名标识
     * @param payment  支持金额
     * @param request
     * @return 符合的礼包集合
     */
    public List<GiftTarget> zcActivityGiftTarget(String targetId, Project project, boolean giftFlag, Float payment, List<GiftMember> giftMembers, HttpServletRequest request) {
        ExpressionParser parser = new SpelExpressionParser();
        EvaluationContext ctx = new StandardEvaluationContext();
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        List<GiftTarget> giftTargets = Lists.newArrayList();
        if (project.getAuthorId().equals(currentUser.getId())) { // 众筹者
            List<GiftTarget> targets = giftTargetService.list(new GiftTarget(null, targetId, null));
            for (GiftTarget giftTarget : targets) {
                // 众筹成功礼包
                if (giftTarget.getCondition().equals(TargetCondition.ZC_SUCCESS.getCode()) && project.getIsSuccess().equals(1)) {
                    boolean result = this.checkIsOrder(currentUser.getId(), giftTarget.getGiftId(), targetId);
                    if (result) {
                        giftTargets.add(giftTarget);
                    }
                }
                // 众筹报名礼包
                else if (giftTarget.getCondition().equals(TargetCondition.ZC_APPLY.getCode()) && project.getIsSuccess().equals(0) && giftFlag) {
                    boolean result = this.checkIsOrder(currentUser.getId(), giftTarget.getGiftId(), targetId);
                    if (result) {
                        giftTargets.add(giftTarget);
                    }
                }
                // 众筹鼓励礼包 一个礼包只能领取一次，如果要领取多个，最好是配多个礼包
                else if (giftTarget.getCondition().equals(TargetCondition.ZC_ING.getCode())) {
                    ctx.setVariable("totalMoney", project.getActualAmount());
                    boolean result = this.checkIsOrder(currentUser.getId(), giftTarget.getGiftId(), targetId);
                    if (result) {
                        result = checkMoney(giftTargets, parser, ctx, giftTarget);
                        if (!result) {
                            giftTargets.remove(giftTarget);
                        }
                    }
                }
                // 众筹支持
                else if (giftTarget.getCondition().equals(TargetCondition.ZC_SUPPORT.getCode())) {
                    this.checkSupportGift(payment, parser, ctx, giftTargets, giftTarget);
                }
            }
        } else { // 支持者
            // 该众筹的累计支持金额，满足条件触发礼包
            GiftTarget giftTarget = giftTargetService.getUnique(new GiftTarget(TargetCondition.ZC_SUPPORT.getCode(), targetId, null));
            if (giftTarget != null) {
                this.checkSupportGift(payment, parser, ctx, giftTargets, giftTarget);
            }
        }
        return giftTargets;
    }

    /**
     * 检查支持者礼包
     *
     * @param payment     支付金额
     * @param parser      表达式解析器
     * @param ctx         ctx域
     * @param giftTargets 礼包集合
     * @param giftTarget  关系
     */
    private void checkSupportGift(Float payment, ExpressionParser parser, EvaluationContext ctx, List<GiftTarget> giftTargets, GiftTarget giftTarget) {
        if (null != payment && payment > Float.valueOf(0.0f)) {
            // Float totalMoney = supportService.sumByProjectId(projectId, currentUser.getId());
            ctx.setVariable("totalMoney", payment);
            this.checkMoney(giftTargets, parser, ctx, giftTarget);
        }
    }

    /**
     * 检查金额是否满足触发条件
     *
     * @param giftTargets 礼包集合
     * @param parser      表达式解析器
     * @param ctx         ctx域
     * @param giftTarget  关系
     */
    private boolean checkMoney(List<GiftTarget> giftTargets, ExpressionParser parser, EvaluationContext ctx, GiftTarget giftTarget) {
        String conditionParams = giftTarget.getConditionParams();
        if (conditionParams.indexOf("{money}") != -1) {
            conditionParams = conditionParams.replace("{money}", "#totalMoney");
            conditionParams += "f";
        }
        logger.info("礼包表达式：{}", conditionParams);
        Boolean result = (Boolean) parser.parseExpression(conditionParams).getValue(ctx);
        if (result) {
            giftTargets.add(giftTarget);
        }
        return result;
    }

    /**
     * 检查用户有没有领取过该礼包
     *
     * @param memberId 用户id
     * @param giftId   礼包id
     * @param targetId 项目id
     * @return
     */
    public boolean checkIsOrder(String memberId, String giftId, String targetId) {
        GiftOrder giftOrder = giftOrderService.getUnique(new GiftOrder(memberId, giftId, targetId));
        // giftOrder != null 表示已领取；giftMember != null 表示已添加了关系
        // 只有没有领取过，同时没有添加过关系的才能保存关系
        if (giftOrder == null) {
            GiftMember giftMember = giftMemberService.getUnique(new GiftMember(giftId, memberId, targetId));
            if (giftMember == null) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
}
